package com.example.es_promotion.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class CacheService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    private static final String PROMOTION_CACHE_PREFIX = "promotion:";
    private static final long CACHE_TTL = 30; // 30分钟
    
    @Cacheable(value = "promotions", key = "#promotionId")
    public Object getPromotionFromCache(Long promotionId) {
        // 缓存未命中时返回null，由调用方处理
        return null;
    }
    
    @CacheEvict(value = "promotions", key = "#promotionId")
    public void evictPromotionCache(Long promotionId) {
        log.info("Evicted promotion cache for ID: {}", promotionId);
    }
    
    public void cacheCartPromotions(String cartKey, Object promotions) {
        try {
            redisTemplate.opsForValue().set(cartKey, promotions, CACHE_TTL, TimeUnit.MINUTES);
            log.info("Cached cart promotions for key: {}", cartKey);
        } catch (Exception e) {
            log.error("Failed to cache cart promotions: {}", e.getMessage());
        }
    }
    
    public Object getCachedCartPromotions(String cartKey) {
        try {
            return redisTemplate.opsForValue().get(cartKey);
        } catch (Exception e) {
            log.error("Failed to get cached cart promotions: {}", e.getMessage());
            return null;
        }
    }
}